package com.my.java_web.dao.impl;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//import org.apache.commons.beanutils.BeanUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.my.java_web.dao.UserDao;
import com.my.java_web.domain.User;
import com.my.java_web.util.JdbcUtil;


/*用户数据库操作类
@author my*/

public class UserDaoImpl implements UserDao{
	String url = "jdbc:mysql://127.0.0.1:3306/java-web";
	String username = "root";
	String pw = "123456";

	@Override
	public void add(User user) {
		// TODO Auto-generated method stub		
		String names = "";
		String values = "";
		names = names + "account, " + "name, " + "password, " + "age, " + "sex";
		values = values 
				+ "'" + user.getAccount() + "'" + ", " 
				+ "'" + user.getName() + "'" + ", " 
				+ "'" + user.getPassword() + "'" + ", " 
				+ "'" + user.getAge() + "'" + ", " 
				+ "'" + user.getSex() + "'";
		String sql = "insert into user (" + names + ") values (" + values + ")";
		JdbcUtil.execute(sql);
	}

	@Override
	public void mod(User user) {
		// TODO Auto-generated method stub
		String sql = "update user set account = '"
				+ user.getAccount()+"',password='" 
				+ user.getPassword()+"',age = " 
				+ user.getAge()	+ ", sex = " + user.getSex() 
				+" where id = " + user.getId();
		System.out.println("mod sql: " + sql);
		JdbcUtil.execute(sql);		
	}

	@Override
	public void del(User user) {
		// TODO Auto-generated method stub
		String sql = "delete from user where id = " + user.getId();
		JdbcUtil.execute(sql);
		
	}

	@Override
	public List<User> query(User user) {
		// TODO Auto-generated method stub
		String sql = "select * from user";
		List<User> res= new ArrayList<>();
		List<Map<String, String>> set = JdbcUtil.executeQuery(sql);
//		for (Map<String, String> m : set) {
//			User tmpUser = new User();
//			try {
//				BeanUtils.populate(tmpUser, m);
//			} catch (IllegalAccessException | InvocationTargetException e) {
//				e.printStackTrace();
//			}
//			res.add(tmpUser);
//		}
		for (Map<String,String> m : set) {
			//ͨ��json�ķ�ʽ��mapת��Ϊjson��Ȼ���ٰ�json����ת��Ϊjavabean
			User tmpUser =  JSONObject.toJavaObject((JSON)JSON.toJSON(m), User.class);
			res.add(tmpUser);
		}
	
		return res;
	}

	@Override
	public int login(User user) {
		// TODO Auto-generated method stub
		String sql = "select count(1) as userCount from user " 
				+ " where account = '" + user.getAccount() 
				+ "' and password = '" + user.getPassword() +"'";
		List<Map<String, String>> res = JdbcUtil.executeQuery(sql);
		String count = res.get(0).get("userCount");
		return Integer.parseInt(count);
	}

}
